package juc.executors;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ExecutorExample2 {
    public static void main(String[] args) throws InterruptedException {
        //运行命令dxdiag，DirectX诊断工具
        //Optional.of(Runtime.getRuntime().availableProcessors())
        //        .ifPresent(System.out::println);

        /**
         * return new ForkJoinPool
         *             (Runtime.getRuntime().availableProcessors(),
         *              ForkJoinPool.defaultForkJoinWorkerThreadFactory,
         *              null, true);
         * 返回ExecutorService，ExecutorService可以submit Callable和Runnable
         * ForkJoinPool submit的是RecursiveAction和RecursiveTask
         * 执行完会销毁
         */
        ExecutorService executorService = Executors.newWorkStealingPool();

        List<Callable<String>> callableList = IntStream.range(0, 20).boxed().map(i ->
                (Callable<String>) () -> {
                    System.out.println("同时有多少个 " + Thread.currentThread().getName());
                    timeSleep(2);
                    return "Task-" + i;
                }
        ).collect(Collectors.toList());
        //不会立即得到结果
        //List<Future<String>> futureList = executorService.invokeAll(callableList);
        executorService.invokeAll(callableList).stream().map(future -> {
            try {
                return future.get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).forEach(System.out::println);

    }

    private static void timeSleep(long time) {
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
